package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.model.CartInfo;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: 小兰
 * @Date: 2023/5/5 18:22
 */
@RestController
@RequestMapping("/api/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 将商品放入购物车
     * @param request
     * @param skuId
     * @param skuNum
     * @return
     */
    @GetMapping("/addToCart/{skuId}/{skuNum}")
    public Result addToCart(HttpServletRequest request, @PathVariable("skuId") Long skuId, @PathVariable("skuNum") Integer skuNum){
        //获取用户ID(真实用户ID或者临时用户ID)
        //1.优先使用登陆后用户ID
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isBlank(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartService.addToCart(userId,skuId,skuNum);
        return  Result.ok();
    }

    /**
     * 查询当前用户(登录用户,临时用户)购物车商品列表
     * @param request
     * @return
     */
    @GetMapping("/cartList")
    public Result getCartList(HttpServletRequest request){
        //获取用户ID(真实用户ID或者临时用户ID)
        //1.优先使用登陆后用户ID
        String userId = AuthContextHolder.getUserId(request);
        //2.用户未登录在获取临时用户Id
        String userTempId = AuthContextHolder.getUserTempId(request);

        List<CartInfo> cartInfoList = cartService.getCartList(userId,userTempId);
        return  Result.ok(cartInfoList);
    }

    /**
     * 修改购物车商品选中状态
     * @param request
     * @param skuId
     * @param isChecked
     * @return
     */
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result updateCheck(HttpServletRequest request, @PathVariable("skuId") Long skuId, @PathVariable("isChecked") int isChecked){

        //获取用户ID(真实用户ID或者临时用户ID)
        //1.优先使用登陆后用户ID
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isBlank(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartService.updateCheck(userId,skuId,isChecked);
        return  Result.ok();
    }

    /**
     * 删除购物车中商品
     * @param request
     * @param skuId
     * @return
     */
    @DeleteMapping("/deleteCart/{skuId}")
    public Result deleteCart(HttpServletRequest request, @PathVariable("skuId") Long skuId){

        //获取用户ID(真实用户ID或者临时用户ID)
        //1.优先使用登陆后用户ID
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isBlank(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartService.deleteCart(userId,skuId);
        return  Result.ok();
    }
}
